﻿using Blog.Models.Entitys;
using Blog.Models.ViewModels;
using SqlSugar;
using System.Linq.Expressions;

namespace Blog.Repository.Base
{
    public class BaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity : BaseEntity, new()
    {
        private readonly ISqlSugarClient _db;

        public ISqlSugarClient Db => _db;

        public BaseRepository(ISqlSugarClient db)
        {
            _db = db;
        }

        public async Task<int> BatchDelete(IList<int> ids)
        {
            return await _db.Deleteable<TEntity>().Where(it => ids.Contains(it.Id)).ExecuteCommandAsync();
        }

        public async Task<int> BatchInsert(IList<TEntity> entities)
        {
            return await _db.Insertable<TEntity>(entities).ExecuteCommandAsync();
        }

        public async Task<int> Delete(int id)
        {
            return await _db.Deleteable(new TEntity { Id = id }).ExecuteCommandAsync();
        }

        public async Task<TEntity> Insert(TEntity entity)
        {
            return await _db.Insertable<TEntity>(entity).ExecuteReturnEntityAsync();
        }

        public async Task<TEntity> Query(int id)
        {
            return await _db.Queryable<TEntity>().Where(it => it.Id == id).FirstAsync();
        }
        public async Task<IList<TEntity>> Query()
        {
            return await _db.Queryable<TEntity>().ToListAsync();
        }
        public async Task<IList<TEntity>> Query(IList<int> ids)
        {
            return await _db.Queryable<TEntity>().Where(it => ids.Contains(it.Id)).ToListAsync();
        }

        public async Task<IList<TEntity>> Query(Expression<Func<TEntity, bool>> expression)
        {
            return await _db.Queryable<TEntity>().Where(expression).ToListAsync();
        }

        public async Task<PageList<TEntity>> QueryPage(Expression<Func<TEntity, bool>>? expression, int pageIndex = 1, int pageSize = 5)
        {
            RefAsync<int> total = 0;
            List<TEntity> data = await _db.Queryable<TEntity>().WhereIF(expression != null, expression).ToPageListAsync(pageIndex, pageSize, total);
            return new PageList<TEntity> { Data = data, Total = total };
        }

        public async Task<TEntity> Update(TEntity entity)
        {
            await _db.Updateable(entity).ExecuteCommandAsync();
            return entity;
        }
        public async Task<IList<TEntity>> BatchUpdate(IList<TEntity> entities)
        {
            await _db.Updateable<TEntity>(entities).ExecuteCommandAsync();
            return entities;
        }


    }
}
